// api/house.js
import request from "../request";

export default {
  getHouses(params = {}) {
    // 参数标准化
    const processed = {
      city: params.city || "",
      rentType: params.rentType || "",
      minRent: params.minRent ? Number(params.minRent) : undefined,
      maxRent: params.maxRent ? Number(params.maxRent) : undefined,
      title: params.title || "",
      sortBy: params.sortBy || "createTime",
      order: (params.order || "desc").toLowerCase(),
      page: Math.max(Number(params.page) || 1, 1),
      size: Math.min(Math.max(Number(params.size) || 10, 1), 100),
      id: params.id || undefined,
      status: params.status || undefined,
      ownerId: params.ownerId || undefined,
    };

    // 过滤空值
    const finalParams = Object.fromEntries(
      Object.entries(processed).filter(([_, v]) => v !== undefined && v !== "")
    );

    return request.get("/api/houses/getHouses", { params: finalParams });
  },
  addHouse(userId, formData, config) {
    return request.post(`/api/houses/add/${userId}`, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
        ...config?.headers,
      },
      ...config,
    });
  },
  updateHouse(id, formData) {
    // 添加身份验证头
    const config = {
      headers: {
        "Content-Type": "multipart/form-data",
        Authorization: `Bearer ${localStorage.getItem("access_token")}`,
      },
    };
    // 更健壮的参数处理
    return request
      .put(`/api/houses/update/${id}`, formData, config)
      .catch((error) => {
        console.error("更新请求失败:", error.response?.data || error.message);
        throw error;
      });
  },
  updateStatus(houseId, status) {
    return request.put(`/api/houses/updateStatus/${houseId}/${status}`);
  },
  getHousesByOwnerId(ownerId) {
    return request.get(`/api/houses/getHousesByOwnerId`, {
      params: {
        ownerId: ownerId,
      },
    });
  },
};
